import store from '@/store';
import REST_URL from '@/http/http.restUrl';


interface IUsePay {
	wxPay : (amount : string, order_num : string, openid : string) => Promise<number>
}

interface IGetWxPayOptionsParams {
	customer_id : number;
	amount : string;
	order_num : string;
	openid : string;
}

interface IGetWxPayOptionsResult {
	timeStamp : number;
	order_num : string;
	package : {
		prepay_id : string;
	}
	nonceStr : string;
	signType : string;
	paySign : string;
}


function usePay() : IUsePay {

	console.log('wxe7fdd55ef90ec1f2')

	const WXPayOfficial = (options : IGetWxPayOptionsResult) => {
		return new Promise((resolve, reject) => {

			const requestPaymentOptions : WeixinJSBridge.WxBridgeInvoke = {
				appId: "wx44b35d013a63718d",
				timeStamp: `${options.timeStamp}`,
				package: `prepay_id=${options.package.prepay_id}`,
				signType: 'RSA',
				nonceStr: options.nonceStr,
				paySign: options.paySign,
			}

			WeixinJSBridge.invoke("getBrandWCPayRequest", requestPaymentOptions, (res) => {
				console.log('微信支付res=======>', res);
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					console.log('微信支付成功>>>>>>>>>>>>>>>>>', res)
					resolve(res)
				} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
					res.wxpay_err_code = 504;
					reject(res);
				} else if (res.err_msg == "get_brand_wcpay_request:fail") {
					WeixinJSBridge.call("closeWindow");
					res.wxpay_err_code = 505;
					reject(res);
				} else {
					res.wxpay_err_code = 506;
					reject(res);
				}
			})
		})
	}

	const WXPayH5 = (options : IGetWxPayOptionsResult) => {
		return new Promise((resolve, reject) => {
			uni.prompt.$showToast('WXPayH5')
		})
	}

	const isWx = () => {
		let uAgent = navigator.userAgent.toLowerCase();
		return /micromessenger/.test(uAgent) ? true : false;
	}

	const wxPay = async (amount : string, order_num : string, openid : string) => {

		await uni.loginManger.$interceptor;
		const params : IGetWxPayOptionsParams = {
			amount,
			order_num,
			openid,
			customer_id: store.state.userInfo!.id,
		}
		console.log('params============>', params);
		try {
			var result : IGetWxPayOptionsResult = (await uni.http.POST(REST_URL.getWxPayOptions, params)).data;
			console.log('result========>', result)
			if (isWx()) {
				await WXPayOfficial(result);
			} else {
				await WXPayH5(result)
			}
			console.log('支付成功');
			return Promise.resolve(200);
		} catch (e) {
			uni.prompt.$showToast('支付失败');
			if (!e.wxpay_err_code) {
				console.log('获取微信支付参数失败', e);
				return Promise.reject(503);
			} else if (e.wxpay_err_code === 504) {
				console.log('用户取消微信支付', e);
				return Promise.reject(e.wxpay_err_code);
			} else if (e.wxpay_err_code === 505) {
				console.log('用户微信支付失败', e);
				return Promise.reject(e.wxpay_err_code);
			} else if (e.wxpay_err_code === 506) {
				console.log('调用微信支付失败', e);
				return Promise.reject(e.wxpay_err_code);
			}
		}
	}


	return {
		wxPay
	}
}


export {
	usePay
}